package com.example.stock.controller;

import com.example.stock.annotation.TokenToUser;
import com.example.stock.controller.param.UserLoginParam;
import com.example.stock.entity.User;
import com.example.stock.service.StockOperationService;
import com.example.stock.service.UserService;
import com.example.stock.util.Result;
import com.example.stock.util.ResultGenerator;
import jakarta.validation.Valid;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Log4j2
@CrossOrigin(origins = "*")
@RequestMapping("user")
@RestController
public class UserController {

    @Autowired
    StockOperationService stockOperationService;

    @Autowired
    UserService userService;

    @GetMapping("{stock}")
    Result stockOperation(@PathVariable("stock") String stock, @TokenToUser User user) {
        log.info("stockOperation: " + user);
        return ResultGenerator.genSuccessResult(stockOperationService.getWeekFormat(stock));
    }

    @GetMapping("info")
    Result getUserInfo(@TokenToUser User user) {
        if (user == null) {
            return ResultGenerator.genErrorResult(200, "未登录");
        };
        String nickName = user.getNickName();
        return ResultGenerator.genSuccessResult(Map.of("nickName", nickName));
    }

    @PostMapping("login")
    Result login(@RequestBody @Valid UserLoginParam param) {
        String token = userService.login(param.getLoginName(), param.getPassword());
        if (token == null) {
            return ResultGenerator.genErrorResult(400, "账号密码错误");
        }
        return ResultGenerator.genSuccessResult(Map.of("token",token));
    }
}
